package com.future.mvc.web.exception;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * <P>
 * 局部异常处理
 * 异常处理优先级: 局部异常处理 > 全局异常处理 > SimpleMappingExceptionResolver > tomcat默认机制
 * </p>
 *
 * @author yinhao
 * @version 1.0
 * @since 2024/9/8 19:51
 */
@Controller
public class FutureExceptionHandler {

    @Autowired
    private HttpServletRequest request;

    @RequestMapping("/testEx1")
    public String exception1(Integer num) {
        int i = 9 / num;
        return "success";
    }

    @RequestMapping("/testEx2")
    public String exception2() {
        Integer.parseInt("abc");
        return "success";
    }

    @RequestMapping("/testEx3")
    public String exception3() {
        throw new AgeException("年龄必须在1-120之间");
    }

    @RequestMapping("/testEx4")
    public String exception4() {
        int[] arr = new int[]{1, 2, 3, 4};
        System.out.println(arr[90]);
        return "success";
    }

    @RequestMapping("/testEx5")
    public String exception5() {
        String str = "hello";
        // StringIndexOutOfBoundsException
        char c = str.charAt(10);
        return "success";
    }


    /**
     * 处理局部异常
     * 只能处理本类产生的异常
     */
    // @ExceptionHandler({ArrayIndexOutOfBoundsException.class, ArithmeticException.class, NullPointerException.class})
    public String localException(Exception e) {
        System.out.println("局部异常信息:" + e.getMessage());
        request.setAttribute("exMsg", e.getMessage());
        return "exception_mes";
    }
}
